package com.project.myxima.data;

import com.project.myxima.interfaces.ISubCallback;
import com.project.myxima.utils.LogUtils;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.album.Announcer;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class SubscribeDao implements  ISubDao{

    private static final String TAG = "SubscribeDao";
    private ISubCallback mISubCallback = null;
    private List<Album> mAlbumList = new ArrayList<>();


    //Single Instance for SubscribeDao
    private SubscribeDao(){}

    private static class InnerHolder {
        private static final SubscribeDao INSTANCE = new SubscribeDao();
    }

    public static SubscribeDao getInstance(){
        return InnerHolder.INSTANCE;
    }
    //==========================================



    @Override
    public void setCallback(ISubCallback callback) {
        mISubCallback = callback;
    }

    @Override
    public void addAlbum(Album album) {
        MyAlbum myAlbum = Album2MyAlbum(album);
        myAlbum.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                LogUtils.d(TAG, Thread.currentThread().getName());
                LogUtils.d(TAG, "s" + objectId);

                //e==null means success
                mISubCallback.onAddSubscribe(e == null);
            }
        });
    }



    @Override
    public void delAlbum(Album album) {
        final MyAlbum myAlbum = Album2MyAlbum(album);
        //1. get all the albums that belongs to this user
        BmobQuery<MyAlbum> query = new BmobQuery<>();
        query.addWhereEqualTo("user", BmobUser.getCurrentUser(BmobUser.class)); //why send class?
        query.addWhereEqualTo("albumId", album.getId());
        query.order("-updatedAt");
        //start query, which return a list with 1 or 0 album.
        query.findObjects(new FindListener<MyAlbum>() {
            @Override
            public void done(List<MyAlbum> list, BmobException e) {
                if (e == null) {
                    if(list.size() > 0){
                        //can myAlbum do delete now
                        myAlbum.delete(list.get(0).getObjectId(), new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                mISubCallback.onDeleteSubscribe(e == null);
                            }
                        });
                    }
                }else{
                    mISubCallback.onDeleteSubscribe(false);
                }
            }
        });

    }

    @Override
    public void getAlbums() {
        BmobQuery<MyAlbum> subAlbums = new BmobQuery<>();
        //subAlbums.addWhereEqualTo("user",BmobUser.getCurrentUser(BmobUser.class));
        subAlbums.order("-updatedAt");
        subAlbums.findObjects(new FindListener<MyAlbum>() {
            @Override
            public void done(List<MyAlbum> list, BmobException e) {
                if(e == null){
                    mAlbumList.clear();
                    for(MyAlbum myAlbum : list){
                        Album album = MyAlbum2Album(myAlbum);
                        mAlbumList.add(album);
                    }

                    //notify the presenter
                    mISubCallback.onSubscribeListLoaded(mAlbumList);
                }else{
                    mISubCallback.onSubscribeListLoadedError();
                    LogUtils.d(TAG,"   getAlbums fail----> " + e.toString());
                }
            }
        });
    }

    @Override
    public void isSubscribed(Album album) {
        // whether an album is subscribed
        BmobQuery<MyAlbum> query = new BmobQuery<>();
        query.addWhereEqualTo("user", BmobUser.getCurrentUser(BmobUser.class));
        query.addWhereEqualTo("albumId", album.getId());

        query.findObjects(new FindListener<MyAlbum>() {
            @Override
            public void done(List<MyAlbum> list, BmobException e) {
                if (e == null) {
                    mISubCallback.isSubscribed(list.size() > 0);
                }
            }
        });

    }

    /**
     * convert Album to MyAlbum
     * @param album
     * @return
     */
    private MyAlbum Album2MyAlbum(Album album) {
        MyAlbum myAlbum = new MyAlbum();
        myAlbum.setCoverUrl(album.getCoverUrlLarge());
        myAlbum.setTitle(album.getAlbumTitle());
        myAlbum.setDescription(album.getAlbumIntro());
        myAlbum.setTracksCount(album.getIncludeTrackCount());
        myAlbum.setPlayCount(album.getPlayCount());
        myAlbum.setAuthorName(album.getAnnouncer().getNickname());
        myAlbum.setAlbumId(album.getId());
        myAlbum.setUser(BmobUser.getCurrentUser(BmobUser.class));
        return myAlbum;
    }

    private Album MyAlbum2Album(MyAlbum myAlbum) {
        Album album = new Album();
        album.setCoverUrlLarge(myAlbum.getCoverUrl());
        album.setAlbumTitle(myAlbum.getTitle());
        album.setAlbumIntro(myAlbum.getDescription());
        album.setIncludeTrackCount(myAlbum.getTracksCount());
        album.setPlayCount(myAlbum.getPlayCount());
        album.setId(myAlbum.getAlbumId());

        Announcer announcer = new Announcer();
        announcer.setNickname(myAlbum.getAuthorName());
        album.setAnnouncer(announcer);
        return album;
    }
}
